import json
import os

inputCasePath = 'D:/SvnDirwc/ibaby-project/ibaby-py/testcase'
outputPath = 'D:/SvnDirwc/ibaby-project/ibaby-cms/src/test/java/mock/testcase'
defaultStr = '\n@Override \n public void before() { }\n@Override \n public void after() {}\n@Override \n public void specialProcess(MvcResult result) throws Exception { } \n'
importStr = "import mock.entity.TestDataForm;\n import org.springframework.test.web.servlet.MvcResult;\n"
paramImportStr = "import mock.entity.Parameter;\nimport java.util.ArrayList;\nimport java.util.List;"


def parseToJava(file):
    try:
        datas = json.load(file)
        for data in datas["datas"]:
            javaStr = "package mock.testcase." + datas["controller"] + ";\n"
            javaStr += importStr
            if "param" in data.keys() and len(data["param"]) > 0:
                javaStr += paramImportStr
            javaStr += "public class " + data["name"] + " extends TestDataForm {\n"
            javaStr += " public " + data["name"] + "() { \n"
            javaStr += "  this.setHttpMethod(\"" + data["method"] + "\"); \n"
            javaStr += "  this.setUrl(\"" + datas["url"] + "\"); \n"
            if "param" in data.keys() and len(data["param"]) > 0:
                javaStr += "  List<Parameter> params = new ArrayList<>(); \n"
                count = 0
                for item in data["param"]:
                    javaStr += "  Parameter parameter" + str(count) + " = new Parameter(\"" + item[
                        "paramName"] + "\", \"" + \
                               item[
                                   "paramValue"] + "\",  \"" + item["paramType"] + "\");\n"
                    javaStr += "  params.add(parameter" + str(count) + ");\n"
                    count += 1
                javaStr += "this.setRequestParams(params);"
            javaStr = javaStr + " \n }" + defaultStr + " \n }"
            print(javaStr)
            filePath = outputPath + "/" + datas["controller"]
            if os.path.exists(filePath):
                open(filePath + "/" + data["name"] + ".java", 'w').write(javaStr)
            else:
                os.mkdir(filePath)
                open(filePath + "/" + data["name"] + ".java", 'w').write(javaStr)
    finally:
        file.close()


if __name__ == '__main__':
    for rt, dirs, files in os.walk(inputCasePath):
        print(rt)
        for d in dirs:
            print("文件夹:" + d)
        for file in files:
            print("文件:" + file)
            parseToJava(open(rt + "/" + file))
            # for item in json.load(open(rt + "/" + file))["param"]:
            #     print(" paramName: " + item["paramName"] + " paramValue: " + item[
            #         "paramValue"] + " paramType: " + item["paramType"])
